import React from 'react'
import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'
import { Button, InputItem, WhiteSpace, Toast } from 'antd-mobile'
import Footer from '../component/footer/footer'
import logo from './logo-login.jpg'
import './index.css'
import { login } from '../../redux/user.redux'

function saydata() {
  console.log('data')
}

function high(fn) {
  return function() {
    console.log('before say data')
    fn()
    console.log('after say data')
  }
}

const hello = high(saydata)
hello()
class Login extends React.Component{
  constructor(props) {
    super(props)
    this.state={
      usernameStyle: '',
      passwrodStyle: '',
      pwd: '',
      user: ''
    }
  }
  
  handleChange = (type, val) => {
    this.setState({
      [type]: val
    })
  }
  handleLogin = () => {
    const { user, pwd } = this.state
    if (!user) {
      Toast.info('用户名不能为空！', 1)
    } else {
      if (!pwd) {
        Toast.info('密码不能为空！', 1)
      } else {
        this.props.login({ user, pwd })
      }
    }
  }
  // 获得焦点
  handleOnFocus(type) {
    if (type === 'username') {
      this.setState({
        usernameStyle: 'input_action'
      })
    } else {
      this.setState({
        passwrodStyle: 'input_action'
      })
    }
  }

  // 失去焦点
  handleOnBlur(type) {
    if (type === 'username') {
      this.setState({
        usernameStyle: ''
      })
    } else {
      this.setState({
        passwrodStyle: ''
      })
    }
  } 

  // 注册
  handleRegister = () => {
    this.props.history.push('/register')
  }
  render() {
    const { usernameStyle, passwrodStyle } = this.state
    return (
      <div className="wrap">
        { this.props.redirectTo ? <Redirect to={ this.props.redirectTo } /> : null}
        <div className="login-box">
          <div className="logoBox">
            <img src={logo} className="logo" alt=""/>
          </div>
          <InputItem placeholder="请输入用户名" onChange={ val => this.handleChange('user', val) } onBlur={ this.handleOnBlur.bind(this, 'username') } onFocus={ this.handleOnFocus.bind(this, 'username') } className={`input ${usernameStyle}`} />
          <WhiteSpace size="xl" />
          <InputItem type="password" placeholder="请输入密码" onChange={ val => this.handleChange('pwd', val)  } onBlur={ this.handleOnBlur.bind(this, 'password') } onFocus={ this.handleOnFocus.bind(this, 'password') } className={`input ${passwrodStyle}`} />
          <WhiteSpace size="xl" />
          <Button onClick={ this.handleLogin } type="primary" className="box log-button">登录</Button>
          <div className="notice">
            <span onClick={this.handleRegister} className="register">立即注册</span>
          </div>
        </div>
        <Footer />
      </div>
    )
  }
}

export default connect(state => state.user, { login })(Login)  